﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_TOOL.Tool.UserControls;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.Common.ValueObject;
using BaseDAO = ERP_RORZE_TOOL.DBAccess.BaseDAO;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_TOOL.Tool.Forms
{
    public partial class frm_BorrowEdit : DevExpress.XtraEditors.XtraForm
    {
        public int Id;
        public DateTime Date;
        public string ToolId;
        public int Quantity;
        public string Staff;
        public string Machine;
        public string Note;
        private ucBorrow parent;
        private DataTable dt = new DataTable();
        private bool firstLoadToolDone;
        private bool firstLoadMachineDone;
        private bool dropDown;
        private DataTable dataTable;
        AutoCompleteStringCollection itemToolID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemStaffID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemMachineID = new AutoCompleteStringCollection();
        private LogUtils log;

        public frm_BorrowEdit(ucBorrow fBorrow)
        {
            InitializeComponent();
            btTAdd.Image = ERP_RORZE_TOOL.Properties.Resources.accept;
            btTCancel.Image = ERP_RORZE_TOOL.Properties.Resources.cancel;
            parent = fBorrow;
            //this.CancelButton = this.btTCancel;
            cmbStaff.LostFocus += cmbStaff_LostFocus;
            cmbToolID.LostFocus += cmbToolID_LostFocus;
            cmbMachine.LostFocus += cmbMachine_LostFocus;
            log = new LogUtils();
        }

        void cmbStaff_LostFocus(object sender, EventArgs e)
        {
            if (cmbStaff.Items.Count <= 0)
            {
                foreach (string s in cmbStaff.AutoCompleteCustomSource)
                {
                    if (cmbStaff.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbStaff.Text = s;
                        break;
                    }
                }

            }

            string sql = "SELECT * FROM  [222_Staff]" +
                         "WHERE StaffID = N'" + cmbStaff.Text + "';";
            dataTable = BaseDAO.ExecuteQuery(sql);
            if (dataTable.Rows.Count > 0)
            {
                txtStaffID.Text = dataTable.Rows[0][ToolConstants.Entities.Staff.FieldName.StaffName].ToString();
            }
            else
            {
                txtStaffID.Text = string.Empty;
            }
        }

        void cmbMachine_LostFocus(object sender, EventArgs e)
        {
            if (cmbMachine.Items.Count <= 0)
            {
                foreach (string s in cmbMachine.AutoCompleteCustomSource)
                {
                    if (cmbMachine.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbMachine.Text = s;
                        break;
                    }
                }

            }

        }

        void cmbToolID_LostFocus(object sender, EventArgs e)
        {
            if (cmbToolID.Items.Count <= 0)
            {
                foreach (string s in cmbToolID.AutoCompleteCustomSource)
                {
                    if (cmbToolID.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbToolID.Text = s;
                        break;
                    }
                }

            }

        }

        private void XtraForm1_Load(object sender, EventArgs e)
        {
            dtpTDate.Value = Date;
            BindDataTool();
            txtTQuantity.Text = Quantity.ToString();
            memoTNote.Text = Note;
            BindDataStaff();
            BindDataMachine();


        }

        private void btTUpdate_Click_1(object sender, EventArgs e)
        {
            UpdateData();
        }

        private void btTCancel_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cmbToolID_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (!cmbToolID.Text.Equals(string.Empty) && firstLoadToolDone)
            //{
            //    string fieldName = ToolConstants.StoreProcedure.FieldName.DaoCu;
            //    string where = ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
            //    string storedName = ToolConstants.StoreProcedure.FTonKhoTongHop;

            //    int instockAtpresent = Utilities.CheckInput(fieldName, storedName, where);

            //    if (instockAtpresent <= 0)
            //    {
            //        MessageBox.Show(ToolConstants.Message.Borrow.ToolOutStock, ToolConstants.Form.MessageBox.Notice, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //        //cmbToolID.Text = cmbToolID.Items[0];
            //    }
            //    else
            //    {
            //        MessageBox.Show(string.Format(ToolConstants.Message.Borrow.ToolInStock, cmbToolID.Text, instockAtpresent.ToString()), ToolConstants.Form.MessageBox.Notice, MessageBoxButtons.OK, MessageBoxIcon.Information);

            //    }
            //}
        }

        private void cmbMachine_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (!cmbMachine.Text.Equals(string.Empty) && firstLoadMachineDone)
            //{
            //    string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
            //    string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.Text + "' and " + ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
            //    string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
            //    string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

            //    int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);

            //    if (number == 0)
            //        MessageBox.Show(string.Format(ToolConstants.Message.Borrow.MachineNotBorrow, cmbMachine.Text, cmbToolID.Text), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    else
            //    {
            //        MessageBox.Show(string.Format(ToolConstants.Message.Borrow.MachineBorrow, cmbMachine.Text, cmbToolID.Text, number.ToString()), ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //    }
            //}
        }

        protected override bool ProcessKeyPreview(ref Message m)
        {
            if (m.Msg == 0x0100 && (int)m.WParam == 13)
            {
                this.ProcessTabKey(true);
            }
            return base.ProcessKeyPreview(ref m);
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            // Add controls for which Arrow keys => focus is not required.
            if ((!dropDown && (ActiveControl is TextBox || ActiveControl is System.Windows.Forms.ComboBox || ActiveControl is System.Windows.Forms.DateTimePicker)))
            {
                switch (keyData)
                {
                    case Keys.Up:
                    case Keys.Down:

                        bool forward = (keyData == Keys.Down);
                        if (this.ProcessTabKey(forward))
                        {
                            return true;
                        }

                        break;
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void cmbMachine_DropDown(object sender, EventArgs e)
        {
            dropDown = true;

            System.Windows.Forms.ComboBox combo = sender as System.Windows.Forms.ComboBox;
            combo.AutoCompleteMode = AutoCompleteMode.None;

            if (combo.Items.Count <= 0)
            {
                Cursor.Current = Cursors.WaitCursor;
                switch (combo.Name)
                {
                    case "cmbToolID":
                        foreach (var item in itemToolID)
                        {
                            cmbToolID.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbMachine":
                        foreach (var item in itemMachineID)
                        {
                            cmbMachine.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbStaff":
                        foreach (var item in itemStaffID)
                        {
                            cmbStaff.Items.Add(item.ToString());

                        }
                        break;

                }
                Cursor.Current = Cursors.Default;


            }
        }

        private void frm_BorrowEdit_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.D)
                {
                    btTAdd.Focus();
                    this.btTAdd.PerformClick();
                }
            }
            else if (e.KeyCode == Keys.End)
            {
                btTAdd.Focus();
            }
            else if (e.KeyCode == Keys.Home)
            {
                dtpTDate.Focus();
            }
        }

        #region Private methods

        private bool GetDataTool(Borrow o)
        {
            #region Check valid

            DataTable dtCheck;

            if (Utilities.IsNullOrEmpty(dtpTDate.Value.ToString()))
            {
                MessageBox.Show(ToolConstants.Message.Borrow.DateCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbToolID.Text))
            {
                MessageBox.Show(ToolConstants.Message.Borrow.ToolIDCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [333_Tool] where [ToolID]=N'" + cmbToolID.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Borrow.ToolIDInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbToolID.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbStaff.Text))
            {
                MessageBox.Show(ToolConstants.Message.Borrow.StaffCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [222_Staff] where [StaffID]=N'" + cmbStaff.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Borrow.StaffIDInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbStaff.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbMachine.Text))
            {
                MessageBox.Show(ToolConstants.Message.Borrow.MachineCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [222_Machine] where [MachineID]=N'" + cmbMachine.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Borrow.MachineIDInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbMachine.Focus();
                return false;
            }


            if (Utilities.IsNullOrEmpty(txtTQuantity.Text.Trim()))
            {
                MessageBox.Show(ToolConstants.Message.Borrow.QuantityCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (int.Parse(txtTQuantity.Text) <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Borrow.QuantityMustGreaterZero, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtTQuantity.Focus();
                return false;

            }

            if (int.Parse(txtTQuantity.Text) > 0)
            {
                string fieldName = ToolConstants.StoreProcedure.FieldName.DaoCu;
                string where = ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
                string storedName = ToolConstants.StoreProcedure.FTonKhoTongHop;

                int instockAtpresent = Utilities.CheckInput(fieldName, storedName, where);

                if ((int.Parse(txtTQuantity.Text) - Quantity) > instockAtpresent)
                {
                    MessageBox.Show(string.Format(ToolConstants.Message.Borrow.WrongQuantity2, cmbToolID.Text, instockAtpresent.ToString(), txtTQuantity.Text), ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtTQuantity.Text = "";
                    txtTQuantity.Focus();
                    return false;

                }

                if ((cmbToolID.Text.ToString() != ToolId) && instockAtpresent < int.Parse(txtTQuantity.Text))
                {
                    MessageBox.Show(string.Format(ToolConstants.Message.Borrow.WrongQuantity, cmbToolID.Text, instockAtpresent.ToString(), txtTQuantity.Text), ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtTQuantity.Text = "";
                    txtTQuantity.Focus();
                    return false;

                }

            }
            #endregion

            o.ID = Id;
            o.Date = dtpTDate.Value.Date;
            o.ToolID = cmbToolID.Text.ToString();
            o.Quantity = int.Parse(txtTQuantity.Text);
            o.StaffID = cmbStaff.Text.ToString();
            o.MachineID = cmbMachine.Text.ToString();
            o.Note = memoTNote.Text;

            return true;
        }

        private void BindDataTool()
        {
            ToolHelper helper = new ToolHelper(new Tools());
            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemToolID.Add(row[ToolConstants.Entities.Tool.FieldName.ToolID].ToString());

            }
            cmbToolID.AutoCompleteCustomSource = itemToolID;
            cmbToolID.Text = ToolId;

            string sql = "SELECT * FROM  [333_Tool]" +
                         "WHERE [333_Tool].ToolID = N'" + ToolId + "';";
            dataTable = BaseDAO.ExecuteQuery(sql);
            if (dataTable.Rows.Count > 0)
            {
                txtToolName.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.ToolName].ToString();
            }
            else
            {
                txtToolName.Text = string.Empty;
            }

            firstLoadToolDone = true;
        }

        private void BindDataStaff()
        {
            StaffHelper helper = new StaffHelper(new Staff());
            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemStaffID.Add(row[ToolConstants.Entities.Staff.FieldName.StaffID].ToString());

            }
            cmbStaff.AutoCompleteCustomSource = itemStaffID;
            cmbStaff.Text = Staff;

            string sql = "SELECT * FROM  [222_Staff]" +
                         "WHERE [222_Staff].StaffID = N'" + Staff + "';";
            dataTable = BaseDAO.ExecuteQuery(sql);
            if (dataTable.Rows.Count > 0)
            {
                txtStaffID.Text = dataTable.Rows[0][ToolConstants.Entities.Staff.FieldName.StaffName].ToString();
            }
            else
            {
                txtStaffID.Text = string.Empty;
            }
        }

        private void BindDataMachine()
        {
            MachineHelper helper = new MachineHelper(new Machine());
            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemMachineID.Add(row[ToolConstants.Entities.Machine.FieldName.MachineID].ToString());

            }
            cmbMachine.AutoCompleteCustomSource = itemMachineID;
            cmbMachine.Text = Machine;
            firstLoadMachineDone = true;
        }

        private void UpdateData()
        {
            BorrowHelper helper = new BorrowHelper(new Borrow());
            if (GetDataTool(helper.ValueObject))
            {

                if (helper.Update() > 0)
                {

                    //write Log
                    log.Table = LogConstant.Table.ToolCutting.Borrow;
                    log.Task = LogConstant.Task.Update;
                    log.Description = helper.ValueObject.ToolID;
                    log.WriteLog();

                    if (!Utilities.MessageConfirmationYesNo(ToolConstants.Message.UpdateSuccessAndQuestion))
                    {
                        this.Close();
                    }
                }
                else
                {

                    Utilities.MessageErrorOk(ToolConstants.Message.UpdateFailed);
                }
                parent.BindDatatoGrid();

            }
        }

        #endregion

        private void cmbMachine_DropDownClosed(object sender, EventArgs e)
        {
            dropDown = false;
            ((System.Windows.Forms.ComboBox)sender).AutoCompleteMode = AutoCompleteMode.Append;

        }

        private void cmbToolID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string sql = "SELECT * FROM  [333_Tool]" +
                             "WHERE [333_Tool].ToolID = N'" + cmbToolID.Text + "';";
                dataTable = BaseDAO.ExecuteQuery(sql);
                if (dataTable.Rows.Count > 0)
                {
                    txtToolName.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.ToolName].ToString();
                }
                else
                {
                    txtToolName.Text = string.Empty;
                }

                if (!cmbToolID.Text.Equals(string.Empty) && firstLoadToolDone)
                {
                    string fieldName = ToolConstants.StoreProcedure.FieldName.DaoCu;
                    string where = ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
                    string storedName = ToolConstants.StoreProcedure.FTonKhoTongHop;

                    int instockAtpresent = Utilities.CheckInput(fieldName, storedName, where);

                    if (instockAtpresent <= 0)
                    {
                        MessageBox.Show(ToolConstants.Message.Borrow.ToolOutStock,
                                        ToolConstants.Form.MessageBox.Notice, MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                        //cmbToolID.Text = cmbToolID.Items[0];
                    }
                    else
                    {
                        MessageBox.Show(
                            string.Format(ToolConstants.Message.Borrow.ToolInStock, cmbToolID.Text,
                                          instockAtpresent.ToString()), ToolConstants.Form.MessageBox.Notice,
                            MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }
                }
            }
        }

        private void cmbMachine_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!cmbMachine.Text.Equals(string.Empty))
                {
                    string fieldName = ToolConstants.StoreProcedure.FieldName.Total;
                    string where = ToolConstants.StoreProcedure.FieldName.MachineID + "='" + cmbMachine.Text + "' and " +
                                   ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
                    string storedName = ToolConstants.StoreProcedure.QTotalMachineAtFactoryBorrow;
                    string tempTableName = ToolConstants.StoreProcedure.TemporaryTables.QTotalMachineAtFactoryBorrow;

                    int number = Utilities.CheckInput(fieldName, storedName, where, true, tempTableName);

                    if (number == 0)
                        MessageBox.Show(
                            string.Format(ToolConstants.Message.Borrow.MachineNotBorrow, cmbMachine.Text, cmbToolID.Text),
                            ToolConstants.Form.MessageBox.Warning, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    else
                    {
                        MessageBox.Show(
                            string.Format(ToolConstants.Message.Borrow.MachineBorrow, cmbMachine.Text, cmbToolID.Text,
                                          number.ToString()), ToolConstants.Form.MessageBox.Warning,
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }



    }
}